#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <linux/atomic.h>

static atomic_t count = ATOMIC_INIT(0);
pthread_spinlock_t g_spinlock;

void* thread1_func(void* arg)
{
    int val = -1;
    FILE* fp = (FILE*)arg;
    atomic_inc(&count);
    val = atomic_read(&count);
    printf("pthread test atomic_inc->%d\n", val);
    pthread_spin_lock(&g_spinlock);
    char* s = "thread1: hello\n";
    fwrite(s, strlen(s), 1, fp);
    pthread_spin_unlock(&g_spinlock);
    return NULL;
}

void* thread2_func(void* arg)
{
    FILE* fp = (FILE*)arg;
    atomic_inc(&count);
    pthread_spin_lock(&g_spinlock);
    char* s = "thread2: hello\n";
    fwrite(s, strlen(s), 1, fp);
    pthread_spin_unlock(&g_spinlock);
    return NULL;
}

int main()
{
    FILE* fp = fopen("test.txt", "wt");
    pthread_spin_init(&g_spinlock, PTHREAD_PROCESS_PRIVATE);
    pthread_t th1;
    pthread_t th2;
    pthread_create(&th1, NULL, thread1_func, fp);
    pthread_create(&th2, NULL, thread2_func, fp);
    pthread_join(th1, NULL);
    pthread_join(th2, NULL);
    pthread_spin_destroy(&g_spinlock);
    fclose(fp);
    return 0;
}
